package com.ksvip.next.components.groovy.autoconfigure;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import com.ksvip.next.components.groovy.annotation.condition.ConditionalOnExistingProperty;
import com.ksvip.next.components.groovy.properties.GroovyRedisLoaderProperties;
import com.ksvip.next.components.groovy.compiler.DynamicCodeCompiler;
import com.ksvip.next.components.groovy.helper.ManualRegisterScriptHelper;
import com.ksvip.next.components.groovy.loader.RedisScriptLoader;
import com.ksvip.next.components.groovy.loader.ScriptLoader;
import com.ksvip.next.components.groovy.registry.ScriptRegistry;


/**
 * 自动配置类
 */
@Configuration
@EnableConfigurationProperties(value = { GroovyRedisLoaderProperties.class })
@ConditionalOnExistingProperty(property = GroovyRedisLoaderProperties.PREFIX + ".enable", value = "true")
public class GroovyRedisLoaderAutoConfiguration {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * <p>
     * 注册基于Redis的ScriptLoader，配置里必须要显示开启该加载器时才注入
     * {@code enhance.groovy.engine.redis-loader.enable}
     * 需要依赖于RedisTemplate，所以项目里必须要配置redis
     * </p>
     */
    @Bean("redisScriptLoader")
    public RedisScriptLoader redisScriptLoader(RedisTemplate<String, String> redisTemplate,
                                               DynamicCodeCompiler dynamicCodeCompiler,
                                               GroovyRedisLoaderProperties groovyRedisLoaderProperties) {
        this.logger.info("loading ScriptLoader type is [{}]", RedisScriptLoader.class);
        return new RedisScriptLoader(redisTemplate, dynamicCodeCompiler, groovyRedisLoaderProperties);
    }

    /**
     * 注入手动注册脚本助手
     */
    @Bean
    public ManualRegisterScriptHelper registerScriptHelper(ScriptRegistry scriptRegistry,
                                                           RedisScriptLoader redisScriptLoader,
                                                           RedisTemplate<String, String> redisTemplate,
                                                           GroovyRedisLoaderProperties groovyRedisLoaderProperties) {
        return new ManualRegisterScriptHelper(scriptRegistry, redisScriptLoader, redisTemplate,
                groovyRedisLoaderProperties);
    }

}
